package com.zhanghe.study.xml_parsing.dom.util;

import org.w3c.dom.*;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * DOM解析xml
 * @author zh
 * @date 2020/12/23 17:16
 */
public class DomUtils {
    public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException {
        Document document = createDefaultDocument();
        buildDoc(document);
        saveToFile(document,"gen.xml");

    }

    public static void readMapper(String fileName){
        InputStream stream = ClassLoader.getSystemResourceAsStream("test.xml");
        Document document = null;
        try {
            document = getDefaultDocument(stream);
        } catch (ParserConfigurationException | IOException | SAXException e) {
            throw new RuntimeException("dom树构建失败",e);
        }
        // 获取mapper节点
        NodeList mapperList = document.getElementsByTagName("mapper");
        for(int i = 0;i<mapperList.getLength();i++){
            Node mapperNode = mapperList.item(i);
            if(mapperNode.hasAttributes()){
                // 找到mapper节点的namespace属性节点
                Node namespace = mapperNode.getAttributes().getNamedItem("namespace");
                // namespace属性节点内容
                System.out.println(namespace.getNodeValue());
            }
            if(mapperNode.hasChildNodes()){
                // mapper节点的子节点
                NodeList childNodes = mapperNode.getChildNodes();
                // 遍历子节点
                for(int j = 0;j<childNodes.getLength();j++){
                    Node childNode = childNodes.item(j);
                    if("resultMap".equals(childNode.getNodeName())){
                        //TODO
                    } else if("select".equals(childNode.getNodeName())){
                        //TODO
                    } else if("insert".equals(childNode.getNodeName())){
                        //TODO
                    }
                }
            }
        }
    }

    public static void buildDoc(Document document){
        // 创建test节点作为根节点
        Element root = document.createElement("test");

        // 创建type属性
        Attr type = document.createAttribute("type");
        type.setNodeValue("test");
        // 创建id节点
        Element id = document.createElement("id");
        // 创建文本节点，并放到id节点中
        id.appendChild(document.createTextNode("001"));
        // 创建name节点
        Element name = document.createElement("name");
        // 创建文本节点，并放到name节点中
        name.appendChild(document.createTextNode("张三"));
        // 设置属性节点
        root.setAttributeNode(type);
        // 将节点放入父节点中
        root.appendChild(id);
        root.appendChild(name);
        document.appendChild(root);
    }

    public static void saveToFile(Document document,String fileName){
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer;
        try {
            transformer = factory.newTransformer();
        } catch (TransformerConfigurationException e) {
            throw new RuntimeException("创建Transformer失败",e);
        }
        // 设置xml属性 只设置了version和ecoding  还需要设置其他属性可以从OutputKeys中查找
        transformer.setOutputProperty(OutputKeys.VERSION,"1.0");
        transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
        // dom数据源
        DOMSource source = new DOMSource(document);
        // 目的地
        StreamResult result = new StreamResult(new File(fileName));
        try {
            // 进行转换
            transformer.transform(source,result);
        } catch (TransformerException e) {
            throw new RuntimeException("输出文件错误",e);
        }
    }

    public static Document createDefaultDocument() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.newDocument();
    }

    public static Document getDefaultDocument(String path) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(path);
    }

    public static Document getDefaultDocument(File file) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(file);
    }

    public static Document getDefaultDocument(InputStream inputStream) throws ParserConfigurationException, IOException, SAXException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        return builder.parse(inputStream);
    }

    public static void desc() throws ParserConfigurationException {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document document = builder.newDocument();
        // 取得指定节点名称的NodeList
        document.getElementsByTagName("");
        // 创建一个指定名称的节点
        document.createElement("");
        // 创建一个文本内容节点
        document.createTextNode("");
        // 创建一个属性
        document.createAttribute("");
    }


}
